<template>
  <el-container class="user-page">
    <el-aside width="220px">
      <el-container>
        <el-header>
          <el-input placeholder="输入关键字进行过滤" v-model="postFilterText" clearable></el-input>
        </el-header>
        <el-main class="nopadding">
          <el-tree ref="posts" class="menu" node-key="postId" default-expand-all :data="postList" :highlight-current="true" :expand-on-click-node="false" :filter-node-method="postFilterNode" @node-click="postClick" v-loading="loading.post"  style="padding: 10px">
            <template #default="{node, data}">
							<span class="custom-tree-node" :class="data.status=='1'?'disabled':''">
								<span class="label">{{ data.postName }}</span>
								<span class="code">{{ data.postCode }}</span>
								<span class="do" v-if="data.id != ''">
									<el-button-group>
										<el-button icon="el-icon-edit" size="small" @click.stop="postModify(node, data)"></el-button>
										<el-button icon="el-icon-delete" size="small" @click.stop="postDelete(node, data)"></el-button>
									</el-button-group>
								</span>
							</span>
						</template>
            </el-tree>
        </el-main>
        <el-footer style="height:51px;text-align: center;">
          <el-button-group style="width: 100%">
            <el-button type="primary" size="small" icon="el-icon-plus" @click="addPost" style="width: 50%">添加岗位</el-button>
            <el-button type="danger" size="small" icon="el-icon-refresh" @click.stop="refreshCache" style="width:50%">刷新缓存</el-button>
          </el-button-group>
				</el-footer>
      </el-container>
    </el-aside>
    <el-container>
      <el-header>
      <div class="left-panel">
        <el-button type="primary" icon="el-icon-plus" @click="selectUser" :disabled="modelId==null"></el-button>
        <!-- <el-button type="primary" icon="el-icon-plus" @click="selectUser" v-auth="'system:post:add'" :disabled="modelId==null"></el-button> -->
        <el-button type="danger" plain icon="el-icon-delete" v-if="selection.length > 0" @click="batchMemberDel" v-auth="'system:post:remove'"></el-button>
      </div>
      <div class="right-panel">
        <div class="right-panel-search">
          <el-input ref="searchInput" v-model="search.keyword" minlength="1" maxlength="20" placeholder="账号/姓名/手机" clearable></el-input>
          <el-button type="primary" icon="el-icon-search" @click="memberSearch"></el-button>
        </div>
      </div>
    </el-header>
      <el-main class="nopadding">
        <jdTable ref="table" :apiObj="apiObj" size="large" @selection-change="selectionChange" :params="params" stripe remoteSort remoteFilter>
          <el-table-column type="selection"></el-table-column>
          <el-table-column label="账号" prop="userName" width="150" fixed="left"></el-table-column>
          <el-table-column label="姓名" prop="nickName" width="150" fixed="left"></el-table-column>
          <el-table-column label="手机号" prop="phone" width="150"></el-table-column>
          <el-table-column label="性别" prop="sex" align="center" width="150">
            <template #default="scope">
              <DictTag :options="dict.sex" :value="scope.row.sex"></DictTag>
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="deptName" min-width="200" show-overflow-tooltip="true"></el-table-column>
          <el-table-column label="状态" prop="status" width="150" align="center">
            <template #default="scope">
              <DictTag :options="dict.status" :value="scope.row.status"></DictTag>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" prop="createTime" width="180"></el-table-column>
          <el-table-column label="操作" fixed="right" align="center" width="150">
            <template #default="scope">
              <el-button-group>
                <!--el-button text :type="scope.row.status?'info':'primary'" @click="table_edit(scope.row, scope.$index)" class="button" :disabled="scope.row.status">编辑</el-button-->
                <el-popconfirm title="确定要删除吗？" @confirm="removeMember(scope.row, scope.$index)">
                  <template #reference>
                    <el-button text type="primary" class="button">删除</el-button>
                  </template>
                </el-popconfirm>
              </el-button-group>
            </template>
          </el-table-column>
        </jdTable>
      </el-main>
    </el-container>
  </el-container>

  <select-dialog v-if="dialog.select" ref="selectDialog" @success="handleSaveSuccess" @closed="dialog.select = false"></select-dialog>
</template>

<script>
import Sortable from "sortablejs"
import saveDialog from "./save"
import selectDialog from "../member/select.vue"
import { permissionAll } from "@/utils/permission"
import tool from "@/utils/tool"
import PinYin from "js-pinyin"

export default {
  name: "post",
  components: {
    saveDialog,
    selectDialog
  },
  data() {
    return {
      dialog: {
        select: false,
        save: false
      },
      dict:{
        sex:[],
        status:[],
      },
      apiObj: this.$API.system.member.listByPost,
      params: {},
      selection: [],
      search: {
        keyword: null
      },
      form: {},
      permissionBtn: false,
      loading: {
        post: false
      },
      modelId: null,
      postList: [],
      postFilterText: '',
    }
  },
  watch: {
    postFilterText(val) {
      this.$refs.posts.filter(val);
    }
  },
  mounted() {
    // 加载配置字典
    this.getDict();
    // 加载岗位列表
    this.getPosts()
  },
  methods: {
    // 加载配置字典
    async getDict() {
      this.dict = {
        sex: await this.Dict.get("sys_user_sex"),
        status: await this.Dict.get("sys_normal_disable")
      }
    },
    // 加载岗位列表
    async getPosts() {
      this.loading.post = true
      var res = await this.$API.system.post.list.get({pageSize: 100})
      if (res.code == 200) {
        this.postList = res.data.rows;
        var allNode ={postName: '全部岗位', postCode: 'All', id: ''}
        this.postList.unshift(allNode);
        this.loading.post = false
      }
    },
    //树过滤
    postFilterNode(value, data){
      if (!value) return true;
      var targetText = data.postName;
      return targetText.indexOf(value) !== -1;
    },
    // 岗位树点击事件
    postClick(data) {
      var params = {
        postId: data.postId
      }
      this.$refs.table.reload(params);
      this.modelId = data.postId;
    },
    // 添加岗位
    addPost(){
      this.$prompt('岗位名称', '新建岗位', {
        inputPlaceholder: '请输入一个方便识别的岗位名称',
        inputPattern: /\S/,
        inputErrorMessage: '岗位名称不能为空'
      })
      .then(async ({ value }) => {
        // 获取拼音首字母
        PinYin.setOptions({ checkPolyphone: false, charCase: 0 })
        var postCode = PinYin.getCamelChars(value)

        var data = {
          postName: value,
          postCode: postCode
        }
        var res = await this.$API.system.post.savePost.post(data);
        if(res.code == 200){
          this.$refs.posts.append({
            postId: res.data,
            postName: data.postName,
            postCode: data.postCode
          });
          this.$message.success("操作成功")
        }else{
          this.$alert(res.msg, "提示", {type: 'error'})
        }
      });
    },
    // 编辑岗位
    async postModify(node, data){
      var postId = data.postId;
      this.$prompt('岗位名称', '编辑岗位', {
        inputPlaceholder: '请输入一个方便识别的岗位名称',
        inputPattern: /\S/,
        inputErrorMessage: '岗位名称不能为空',
        inputValue: data.postName
      })
      .then(async ({ value }) => {
        // 获取拼音首字母
        PinYin.setOptions({ checkPolyphone: false, charCase: 0 })
        var postCode = PinYin.getCamelChars(value)

        var data = {
          postId: postId,
          postName: value,
          postCode: postCode
        }
        var res = await this.$API.system.post.updatePost.put(data);
        if(res.code == 200){
          let updateNode = this.$refs.posts.getNode(node);
          console.log(updateNode)
          if (updateNode) {
            updateNode.data.postName = value
            updateNode.data.postCode = postCode
          }
          this.$message.success("操作成功")
        }else{
          this.$alert(res.msg, "提示", {type: 'error'})
        }
      });
    },
    // 删除岗位
    async postDelete(node, data){
      var res = await this.$API.system.post.delPost.delete(data.postId);
      if (res.code == 200){
        let deleteNode = this.$refs.posts.getNode(node);
        this.$refs.posts.remove(deleteNode);
        this.$message.success("操作成功")
      }else{
        this.$alert(res.msg, "提示", {type: 'error'})
      }
    },
    // 移除用户
    async removeMember(row, index){
      var res = await this.$API.system.member.delUserPost.delete(row.id);
      if (res.code == 200) {
        this.$refs.table.refresh()
        this.$message.success("删除成功")
      } else {
        this.$alert(res.msg, "提示", { type: "error" })
      }
    },
    // 批量移除用户
    batchMemberDel(){
      this.$confirm(`确定要删除选中的 ${this.selection.length} 项吗？删除后数据不可被恢复。`, "提示", {
        type: "warning"
      })
        .then(async () => {
          let ids = this.selection.map((item) => item.id)
          var res = await this.$API.system.member.delUserPost.delete(ids)
          if (res.code == 200) {
            this.$refs.table.refresh()
            this.$message.success("操作成功")
          } else {
            this.$alert(res.msg, "提示", { type: "error" })
          }
          const loading = this.$loading()
          loading.close()
        })
        .catch(() => {})
    },
    refreshCache(){
      this.$confirm('此操作将重置岗位的缓存, 是否要继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await this.$API.system.dict.type.refreshCache.delete();
        this.$message.success("操作成功");
      }).catch(() => {
      });
    },
    // 选择用户
    selectUser(){
      this.dialog.select = true;
      this.$nextTick(() => {
        this.$refs.selectDialog.open(this.modelId);
      })
    },
    //表格选择后回调事件
    selectionChange(selection) {
      this.selection = selection
    },
    // 会员搜索
    memberSearch() {
      this.params.searchValue = this.search.keyword;
    },
    //本地更新数据
    handleSaveSuccess() {
      this.$refs.table.refresh()
    },
  }
}
</script>

<style lang="scss" scoped>
  .menu:deep(.el-tree-node__label) {display: flex;flex: 1;height:100%;}
  .custom-tree-node {display: flex;flex: 1;align-items: center;justify-content: space-between;font-size: 14px;padding-right: 24px;height:100%;}
  .custom-tree-node .code {font-size: 12px;color: #999;}
  .custom-tree-node .do {display: none;}
  .custom-tree-node:hover {color: #409eff;}
  .custom-tree-node:hover .code {display: none;}
  .custom-tree-node:hover .do {display: inline-block;animation: fadeIn;animation-duration: 1s;}
  .custom-tree-node.disabled{text-decoration:line-through; color: #aaa;}
  .custom-tree-node.disabled .code {font-size: 12px;color: #aaa;}
</style>
